<!DOCTYPE html>
<script src=../../resources/testharness.js></script>
<script src=../../resources/testharnessreport.js></script>
<script>

// This test attempts to save and verify MediaStream data in the
// ondataavailable event handler of MediaRecorder.

var checkStreamTracks = function(stream, has_video, has_audio) {
  if (has_video) {
    assert_equals(stream.getVideoTracks().length, 1);
    assert_equals(stream.getVideoTracks()[0].readyState, 'live');
  } else {
    assert_equals(stream.getVideoTracks().length, 0);
  }

  if (has_audio) {
    assert_equals(stream.getAudioTracks().length, 1);
    assert_equals(stream.getAudioTracks()[0].readyState, 'live');
  } else {
    assert_equals(stream.getAudioTracks().length, 0);
  }
};

var makeAsyncTest = function(value, expected) {
  var recorder;

  async_test(function(test) {
    var lastTimestamp = NaN;
    const recorderOnDataAvailable = this.step_func(function(event) {
      // TODO(mcasas): Let the test record for a while.
      // TODO(mcasas): Consider storing recorded data and playing it back.
      if (!isNaN(lastTimestamp)) {
        assert_greater_than(event.timecode, lastTimestamp,
                            "timecode must be increasing");
      }
      lastTimestamp = event.timecode;

      if (recorder.state == "recording") {
        recorder.onstop = recorderOnStopExpected;
        recorder.stop();
      }
    });

    const recorderOnStopExpected = this.step_func_done();

    const recorderOnStopUnexpected = test.unreached_func('Recording stopped.');
    const recorderOnError = test.unreached_func('Recording error.');

    const gotStream = this.step_func(function(stream) {
      checkStreamTracks(stream, value['video'], value['audio']);

      recorder = new MediaRecorder(stream);

      assert_equals(recorder.state, "inactive");
      recorder.ondataavailable = recorderOnDataAvailable;
      recorder.onstop = recorderOnStopUnexpected;
      recorder.onerror = recorderOnError;
      recorder.start();

      assert_equals(recorder.state, "recording");
      recorder.requestData();
    });

    const onError = test.unreached_func('Error creating MediaStream.');
    navigator.webkitGetUserMedia(value, gotStream, onError);
  });
};

generate_tests(makeAsyncTest,
               [["video-only",  {video: true,  audio: false}],
                ["audio-only",  {video: false, audio: true}],
                ["audio-video", {video: true,  audio: true}]]);

</script>
